//
//  LZManageReviewsVideoReviewsViewController.m
//  laziz_Merchant
//
//  Created by xbn_iMac on 2016/12/19.
//  Copyright © 2016年 XBN. All rights reserved.
//

#import "LZManageReviewsVideoReviewsViewController.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "LAReviewTableViewCell.h"
#import "LAReviewHeaderView.h"
#import "LZManageReviewsVideoReviewsHeaderView.h"
#import "LZManageReviewsPromotionVideoListModel.h"
#import "LZManageReviewsPresenter.h"
#import "LAReviewModel.h"
#import "MJRefresh.h"
#import "UITableView+LZTableView.h"
#import "IQKeyboardManager.h"
#import "LZCustomerUserModel.h"
#import "LZReviewsReplyModel.h"

@interface LZManageReviewsVideoReviewsViewController ()<UITableViewDelegate,UITableViewDataSource,LAReviewCellDelegate,ReviewHeaderClickDelegate,UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITableView *table;

@property (strong, nonatomic) LAReviewHeaderView *reviewTypeView;

@property (strong, nonatomic) NSMutableArray *dataArr;

@property (nonatomic, strong) LZManageReviewsPresenter *manageReviewsPresenter;

@property (nonatomic, assign) NSInteger selectedHeaderButtonTag;

@property (nonatomic, assign) int page;
@property (nonatomic, assign) int limit;

@property (nonatomic, strong) UITextField *textField;       // 用于占位的
@property (nonatomic, strong) UITextField *textInputReview; // 显示在键盘上的
@property (nonatomic, strong) UITextField *textTemp;        // 记录点击的textField
@property (nonatomic, assign) BOOL isShowKeyBoard;

@end

@implementation LZManageReviewsVideoReviewsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.umLogPageViewName = @"商户评价视频评论列表页面";
    self.title = LZLocalizedString(@"home_menu_manage_reviews", nil);
    
    [self configBaseData];
    
    [self configReplyTextField];
    
    [self registerCell];
    
    [self addFooterRefresh];
    
    [self createHeaderView];
    
    [self.table.mj_footer beginRefreshing];
    
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - request
/* 评论管理--视频评论信息 */
- (void)requestCommentCount {
    WS(weakSelf)
    [self.manageReviewsPresenter videoCommentInfoWithVideoId:self.restaurantModel.promotionId OnSuccess:^(id data) {
         weakSelf.reviewTypeView.model = data;
    } onFail:^(NSString *fail) {
    }];
}

/* 评价管理--商户评价列表接口 */
- (void)requestVideoReviewListWithType:(NSInteger)type andPage:(int)aPage {
    
    WS(weakSelf)
    
    // 评论类型（0全部，1好评，2差评；不填为全部）
    
    [self.manageReviewsPresenter videoReviewListWithVideoId:self.restaurantModel.promotionId andType:[NSString stringWithFormat:@"%ld",type] andPage:aPage andLimit:self.limit onSuccess:^(id data) {

        [weakSelf.table.mj_footer endRefreshing];

        if (data != nil) {
            NSArray *result = [data copy];
            if (result && type == self.selectedHeaderButtonTag && aPage == weakSelf.page) {
                if (result) {
                    weakSelf.page ++;
                    
                    if (result.count>0) {
                        [weakSelf.dataArr addObjectsFromArray:result];
                        [weakSelf.table reloadData];
                    }
                    else {
                        if (weakSelf.dataArr.count == 0) {
                            [weakSelf.table setNoDataFooterText];
                        }
                        else {
                            [weakSelf.table setNoMoreDataFooterText];
                        }
                        [weakSelf.table.mj_footer endRefreshingWithNoMoreData];
                    }
                }
            }
        }
        
    } onFail:^(NSString *fail) {
        [weakSelf.table.mj_footer endRefreshing];
    }];
}

/* 评论列表--添加回复 */

- (void)requestReplyReviewsWithIndexPath:(NSIndexPath*)indexPath andReplies:(NSString*)replies  {
    
    LAReviewModel *model = self.dataArr[indexPath.section];

    [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:YES];

    WS(weakSelf)
    [self.manageReviewsPresenter replyReviewsWithMessageType:@"1" andReviewsUserId:model.customerUser.userId andCommentId:model.commentId andReplies:replies onSuccess:^(id data) {
        [weakSelf stopLoadingViewForView:weakSelf.view];
        if (model.replies == nil) {
            model.replies = [NSMutableArray array];
        }
        [model.replies addObject:data];
        [weakSelf.table reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        
    } onFail:^(NSString *fail) {
        [weakSelf stopLoadingViewForView:weakSelf.view];
    }];
}

/* 评论列表--删除评论 */
- (void)requestDeleteReplyWithIndexPath:(NSIndexPath*)indexPath {
    LAReviewModel *model = self.dataArr[indexPath.section];
    LZReviewsReplyModel *replyModel = model.replies[0];

    [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:YES];

    WS(weakSelf)
    [self.manageReviewsPresenter deleteReplyReviewsWithReplyId:replyModel.replyId onSuccess:^(id data) {
        [weakSelf stopLoadingViewForView:weakSelf.view];
        [model.replies removeAllObjects];
        model.replies = nil;
        [weakSelf.table reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } onFail:^(NSString *fail) {
        [weakSelf stopLoadingViewForView:weakSelf.view];
    }];
}

#pragma mark - config BaseData

- (void)configBaseData {
    self.page = 1;
    self.limit = 10;
    self.dataArr = [NSMutableArray array];
    self.manageReviewsPresenter = [[LZManageReviewsPresenter alloc] init];
}

#pragma mark - config UI

- (void)registerCell {
    
    [self.table registerNib:[UINib nibWithNibName:@"LAReviewTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    
    self.table.separatorColor = [UIColor clearColor];
    self.table.backgroundColor = UIColorFromRGB(0xeeeeee, 1);
}

/**
 添加上拉刷新
 */
- (void)addFooterRefresh {
    self.table.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upLoadMoreData)];
}

/**
 创建headerView
 */
-(void)createHeaderView {
    
    UIView *headerView = [[UIView alloc] init];
    
    LZManageReviewsVideoReviewsHeaderView *infoView = [[LZManageReviewsVideoReviewsHeaderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 85)];
    infoView.model = self.restaurantModel;
    [headerView addSubview:infoView];
    
    self.reviewTypeView = [[LAReviewHeaderView alloc] init];
    self.reviewTypeView.frame = CGRectMake(0, CGRectGetHeight(infoView.bounds), [self.reviewTypeView intrinsicContentSize].width, [self.reviewTypeView intrinsicContentSize].height);
    self.reviewTypeView.delegate = self;
    
    [headerView addSubview:self.reviewTypeView];
    
    headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, CGRectGetHeight(infoView.bounds)+CGRectGetHeight(self.reviewTypeView.bounds));
    
    self.table.tableHeaderView = headerView;
    
    [self requestCommentCount];
    
}

#pragma mark - privite mathod

- (void)upLoadMoreData {
    [self requestVideoReviewListWithType:self.selectedHeaderButtonTag andPage:self.page];
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LAReviewTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [self configureCell:cell atIndexPath:indexPath];
    
    return cell;
}

- (void)configureCell:(LAReviewTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    cell.fd_enforceFrameLayout = NO; // Enable to use "-sizeThatFits:"
    
    cell.indexPath = indexPath;
    
    cell.textField = self.textField;
    WS(weakSelf)
    cell.isShowKeyBoardStatus = ^BOOL(){
        return weakSelf.isShowKeyBoard;
    };
    
    cell.delegate = self;
    cell.reviewType = ReviewType_Video;
    cell.headImageType = HeadImageType_User;
    
    cell.entity = self.dataArr[indexPath.section];
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    LAReviewModel *model = self.dataArr[indexPath.section];
    
    float height = [tableView fd_heightForCellWithIdentifier:@"cell" cacheByIndexPath:indexPath configuration:^(LAReviewTableViewCell *cell) {
        
        [cell getReviewLabel].numberOfLines = model.labReviewNumberOfLine;
        
        [self configureCell:cell atIndexPath:indexPath];
    }];
    
    return height;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 10;
    }
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

-(void)refreshCellHeight:(NSIndexPath *)indexPath {
    [self.table reloadData];
}

- (void)deleteReplyWithIndex:(NSIndexPath *)indexPath {
    [self requestDeleteReplyWithIndexPath:indexPath];
}

#pragma mark - ReviewHeaderClickDelegate

- (void)clickButton:(UIControl *)button {
    self.selectedHeaderButtonTag = button.tag;
    [self.table.mj_footer endRefreshing];
    [self.dataArr removeAllObjects];
    [self.table reloadData];
    
    self.page = 1;
    self.limit = 10;
    
    [self.table.mj_footer beginRefreshing];
}

#pragma mark - Reply TextField

- (void)configReplyTextField {
    
    self.textInputReview = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
    self.textInputReview.backgroundColor = [UIColor whiteColor];
    self.textInputReview.layer.borderWidth = 0.5;
    self.textInputReview.returnKeyType = UIReturnKeySend;
    self.textInputReview.delegate = self;
    self.textInputReview.layer.borderColor = UIColorFromRGB(0x999999, 1).CGColor;
    
    self.textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
    self.textField.inputAccessoryView = self.textInputReview;
    self.textField.returnKeyType = UIReturnKeySend;
    self.textField.backgroundColor = [UIColor redColor];
    self.textField.hidden = YES;
    self.textField.delegate = self;
    
    
    
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center  addObserver:self selector:@selector(keyboardDidShow)  name:UIKeyboardDidShowNotification  object:nil];
    [center addObserver:self selector:@selector(keyboardDidHide)  name:UIKeyboardWillHideNotification object:nil];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    tap.numberOfTapsRequired = 1;
    [self.table addGestureRecognizer:tap];
}

- (void)tapAction:(UITapGestureRecognizer*)tap {
    
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
    
}

- (void)keyboardDidShow
{
    [IQKeyboardManager sharedManager].enable = NO;
    if (self.textTemp == self.textField && !self.isShowKeyBoard) {
        if (self.textInputReview.isFirstResponder == YES) {
            return;
        }
        self.isShowKeyBoard = YES;
        [self.textInputReview becomeFirstResponder];
    }
}

- (void)keyboardDidHide
{
    self.isShowKeyBoard = NO;
    [IQKeyboardManager sharedManager].enable = YES;
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    self.textTemp = textField;
  
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField == self.textInputReview) {
        [self tapAction:nil];
        
        [self requestReplyReviewsWithIndexPath:[NSIndexPath indexPathForRow:0 inSection:self.textField.tag] andReplies:textField.text];
        DLog(@"发送发送发送");
    }
    return YES;
}

@end
